<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--公共css-->
    <div th:replace="common :: common-css"></div>
    <!--公共js-->
    <div th:replace="common :: common-js"></div>

</head>
<body>

<!--顶部导航-->
<div th:replace="common :: top-nav"></div>
<!--顶部导航-->

<!--左侧导航-->
<!--<div class="col-sm-2">-->
<!--    <ul class="nav nav-pills nav-stacked text-center ">-->
<!--        <li class="active"><a th:href="@{/account/staffinfo}">个人信息</a></li>-->
<!--        <li><a href="javascript:;">导航3</a></li>-->
<!--        <li><a th:href="@{/account/changepwd}">修改密码</a></li>-->
<!--    </ul>-->
<!--</div>-->
<!--左侧导航-->
<div th:replace="common :: common-account-left-nav"></div>

<!--个人信息表单-->
<div class="col-sm-6 col-sm-offset-1">
    <form id="user_info_form" class="form-horizontal" enctype="multipart/form-data">
        <div class="form-group">
            <div class="col-sm-8 col-sm-offset-2 ">
                <a th:href="@{/account/uploadheadphoto}" class="thumbnail">
                    <img id="preImg" title="点击上传头像"  style="width: 134px;">
                    <span id="loginUserPhoto" hidden th:text="${session.loginUserPhoto}"></span>
                </a>
            </div>
        </div>
        <div class="form-group">
            <label for="userName" class="col-sm-2 control-label">账号</label>
            <div class="col-sm-8">
                <input readonly="readonly" type="text" class="form-control" name="userName" id="userName"
                       th:value="${session.loginUserName}">
            </div>
        </div>

        <div class="form-group">
            <label for="first_name" class="col-sm-2 control-label">姓</label>
            <div class="col-sm-8">
                <input type="tel"  autocomplete="off" class="form-control" id="first_name" name="firstName">
                <span class="text-danger hidden "></span>
            </div>
        </div>
        <div class="form-group">
            <label for="last_name" class="col-sm-2 control-label">名</label>
            <div class="col-sm-8">
                <input type="tel"  autocomplete="off" class="form-control" id="last_name" name="lastName">
                <span class="text-danger hidden "></span>
            </div>
        </div>
        <div class="form-group">
            <label for="email" class="col-sm-2 control-label">邮箱</label>
            <div class="col-sm-8">
                <input type="tel"  autocomplete="off" class="form-control" id="email" name="email">
                <span class="text-danger hidden "></span>
            </div>
        </div>
        <div class="form-group">
            <label for="phone" class="col-sm-2 control-label">电话</label>
            <div class="col-sm-8">
                <input type="tel"  autocomplete="off" class="form-control" id="phone" name="phone">
                <span class="text-danger hidden "></span>
            </div>
        </div>

        <div class="form-group">
            <label for="country" class="col-sm-2 control-label">国家</label>
            <div class="col-sm-8">
                <select id="country" class=" form-control" name="country">

                </select>
            </div>
        </div>

        <div class="form-group">
            <input id="addressId" type="text" hidden>
            <label for="city" class="col-sm-2 control-label">城市</label>
            <div class="col-sm-8">
                <div class="col-sm-9" style="padding: 0;">
                    <select id="city" class=" form-control" name="city">

                    </select>
                </div>
                <div class="col-sm-3" style="padding: 0; ">
                    <input id="district" class=" form-control text-center" readonly name="district">
                </div>
            </div>
        </div>
        <div class="form-group">
            <label for="postal_code" class="col-sm-2 control-label">邮编</label>
            <div class="col-sm-8">
                <input type="tel"  autocomplete="off" class="form-control" id="postal_code" name="postalCode">
                <span class="text-danger hidden "></span>
            </div>
        </div>
        <div class="form-group">
            <label for="address1" class="col-sm-2 control-label">详细地址1</label>
            <div class="col-sm-8">
                <input type="tel" autocomplete="off" class="form-control" id="address1" name="address1">
                <span class="text-danger hidden "></span>
            </div>
        </div>
        <div class="form-group">
            <label for="address2" class="col-sm-2 control-label">详细地址2</label>
            <div class="col-sm-8">
                <input type="tel" autocomplete="off"  class="form-control" id="address2" name="address2">
                <span class="text-danger hidden "></span>
            </div>
        </div>

        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <button type="button" id="changeInfo_submitBtn" class="btn  disabled">修改</button>
                <button type="button" id="reloadInfo" class="btn btn-primary hidden">重置</button>
            </div>
        </div>

        <div class="alert alert-danger alert-dismissible hidden">
            <button type="button" class="close" data-dismiss="alert">
                <span>&times;</span>
            </button>
            <strong>Warning!</strong><span>Better check yourself, you're not looking too good.</span>
        </div>
    </form> <!--</form>-->

</div>
<!--个人信息表单-->



</body>
<script>
    $(document).ready(function () {
        $("#left_bar_staffinfo").addClass("active");

        //获取项目,带斜杠如:/项目名
        projectName = window.document.location.pathname.match(/^[/]{1}\w*/);
        staffInfo = initPage();

        initPhoto();//头像初始化

        //切换国家操作
        $("#country").change(function () {
            let changeName = $(this).val();//当前选中的国家
            let reloadCity = ""; //重新填充city
            for (let i = 0; i < countryLis.length; i++) {
                if (changeName == countryLis[i]["countryName"]) {
                    for (let j = 0; j < countryLis[i]["cityList"].length; j++) {
                        reloadCity += "<option value ='" + countryLis[i]["cityList"][j]["cityId"] + "'>" + countryLis[i]["cityList"][j]["cityName"] + "</option>";
                    }
                }
            }
            $("#city").html(reloadCity);
        });

        //监听整个form表单是否有变化,有的话修改按钮变为可用
        $("#user_info_form").change(function () {
            $("#changeInfo_submitBtn").addClass("btn-success");
            $("#changeInfo_submitBtn").removeClass("disabled");
            $("#reloadInfo").removeClass("hidden");
        });

        /**
         账号(不能修改)
         地址id(不能修改,且是隐藏域)
         姓
         名
         邮箱
         电话
         邮编
         详细地址1
         详细地址2
         (头像,国家,省,城市,需额外操作)
         **/
        //修改个人信息按钮
        $("#changeInfo_submitBtn").click(function () {
            //目前表单中的数据,去除前后空格
            let infoObj = {
                addressId: $.trim($("#addressId").val()),
                userName: $.trim($("#userName").val()),
                firstName: $.trim($("#first_name").val()),
                lastName: $.trim($("#last_name").val()),
                email: $.trim($("#email").val()),
                phone: $.trim($("#phone").val()),
                postalCode: $.trim($("#postal_code").val()),
                address1: $.trim($("#address1").val()),
                address2: $.trim($("#address2").val()),
                cityId: $.trim($("#city").val())
            };
            for (let key in infoObj) {
                if (key == "userName" || key == "addressId") {
                    //账号作为修改的依据,且不能修改,故跳过
                    //地址id同理
                    continue;
                }
                //如果为空则删除这个属性
                if (infoObj[key] == "" || infoObj[key] == null || infoObj[key] == undefined) {
                    delete infoObj[key];
                }
                //如果和原始数据一样,也删除这个属性
                if (infoObj[key] == staffInfo[key]) {
                    delete infoObj[key];
                }
            }

            //真正改变过的东西 且>2,因为userName和addressId肯定有
            if (infoObj != undefined && Object.keys(infoObj).length > 2) {
                $.ajax({
                    url: projectName + "/userController/changeStaffInfo",
                    type: "POST",
                    data: infoObj,
                    success: function (msg) {
                        alert(msg);
                        window.location.href = window.location.href;
                    }
                });
            }
        /*
            let picture = $("#picture_upload")[0].files[0] || null;//头像,是否改变过
            if (picture != null) {//头像上传
                if (picture.size > (50 * 1024)) {//不能超过50K
                    alert("不能超过50K")
                } else if ((/jpeg/.test(picture.type))) {
                    alert(picture.type);
                    $("#picture_upload_form").submit();
                } else {
                    alert("只能上传图片");
                }
            }
*/

        });

        //重置按钮
        $("#reloadInfo").click(function () {
            initPage();
            $("#changeInfo_submitBtn").removeClass("btn-success");
            $("#changeInfo_submitBtn").addClass("disabled");
            $("#reloadInfo").addClass("hidden");
        });
    });

    //初始化页面
    function initPage() {
        let $userName = $("#userName").val();
        let info;
        $.ajax({
            url: projectName + "/userController/getStaffInfoByStaffUserName",
            type: "POST",
            async: false,//改为同步
            data: {"userName": $userName},
            success: function (result) {
                info = result;
                $("#addressId").val(result["addressId"]);
                $("#first_name").val(result["firstName"]);
                $("#last_name").val(result["lastName"]);
                $("#email").val(result["email"]);
                $("#phone").val(result["phone"]);
                $("#postal_code").val(result["postalCode"]);
                $("#address1").val(result["address1"]);
                $("#address2").val(result["address2"]);
                $("#address2").val(result["address2"]);
                $("#district").val(result["district"]);
                let currentCountry = result["country"];
                let currentCity = result["city"];
                countryLis = getAllCountryAndCity();//返回全局变量
                selectLoad(currentCountry, currentCity);
            }
        });
        return info;
    }

    //查询所有国家,每个国家对应多个城市
    function getAllCountryAndCity() {
        let countryList;
        $.ajax({
            url: projectName + "/userController/getAllCountryAndCity",
            type: "POST",
            async: false, //改为同步
            success: function (result) {
                countryList = eval(result);
            }
        });
        return countryList;
    }

    //填充国家和城市的<select>,传入当前国家和当前城市
    function selectLoad(currentCountry, currentCity) {
        let countryOption = "";
        let cityOption = "";
        for (let i = 0; i < countryLis.length; i++) {
            if (currentCountry == countryLis[i]["countryName"]) {
                countryOption += "<option selected='selected' value ='" + countryLis[i]["countryName"] + "'>" + countryLis[i]["countryName"] + "</option>";

                let cityList = countryLis[i]["cityList"];//这个国家的城市列表
                for (let j = 0; j < cityList.length; j++) {
                    if (currentCity == cityList[j]["cityName"]) {
                        cityOption += "<option selected='selected' value ='" + cityList[j]["cityId"] + "'>" + cityList[j]["cityName"] + "</option>";
                    } else {
                        cityOption += "<option value ='" + cityList[j]["cityId"] + "'>" + cityList[j]["cityName"] + "</option>"
                    }
                }
            } else {
                countryOption += "<option value ='" + countryLis[i]["countryName"] + "'>" + countryLis[i]["countryName"] + "</option>";
            }
        }

        $("#country").html(countryOption);
        $("#city").html(cityOption);
    }

    //初始化头像
    function initPhoto() {
        //返回当前协议  http:  (没有斜杠)
       let projectProtocol=window.document.location.protocol;
        //返回host, localhost:8888 (没有斜杠)
       let projectHost=window.document.location.host;
        //获取头像位置  /位置/xxxx.jpg
        let imgLocal=$("#loginUserPhoto").text();

        if (imgLocal!=""){
            //拼接成格式  http://localhost:8888/mysql_sakila/user_files/unnamed.jpg
            let fullPath=projectProtocol+"//"+projectHost+projectName+imgLocal;
            $("#preImg").attr("src",fullPath);
        } else {
            //当前用户没有图片,则默认图片
            $("#preImg").attr("src","");
        }
    }
    /*
    Staff(staffId=4,
          firstName=狗,
          lastName=春,
          addressId=4,
          country=Australia,
          district=QLD,
          city=Woodridge,
          address1=1411 Lillydale Drive,
          address2=null,
          postalCode=,
          phone=6172235589,
          picture=null,
          email=xxxxxx@163.com,
          storeId=2,
          active=1,
          userName=dog,
          passWord=null,
          salt=null,
          lastUpdate=null,
          roleName=null,
          roleType=null)
     */
    /**
     * Country(countryId=1,
     * countryName=Afghanistan,
     * cityList=[City(cityId=251, cityName=Kabul)])
     */
</script>
</html>